<?php

namespace Payment\Notify;

use Payment\Common\YSEConfig;
use Payment\Common\PayException;
use Payment\Config;
use Payment\Utils\ArrayUtil;

class YSENotify extends NotifyStrategy{

    /**
     * SwNotify constructor.
     *
     * @param array $config
     * @throws PayException
     */
    public function __construct(array $config){
        parent::__construct($config);
        try{
            $this->config = new YSEConfig($config);
        }catch(PayException $e){
            throw $e;
        }
    }

    /**
     * 获取移除通知的数据  并进行简单处理（如：格式化为数组）
     * 如果获取数据失败，返回false
     *
     * @return array|false
     */
    public function getNotifyData(){
        $params = array();
        //支持直接读取input流
        // $data = @file_get_contents('php://input');
        $data = $_POST;
        if(!empty($data)){
            // $inputArray = json_decode($data, true);
            $params = array_merge($params, $data);
        }
        if(count($params) < 1){//如果参数为空,则不进行处理
            return false;
        }
        return $params;
        // TODO: Implement getNotifyData() method.
    }

    /**
     * 检查异步通知的数据是否合法
     * 如果检查失败，返回false
     *
     * @param array $data 由 $this->getNotifyData() 返回的数据
     * @return boolean
     * @throws \Exception
     */
    public function checkNotifyData(array $data){
        return $this->verifySign($data);
    }

    /**
     * 检查数据是否被篡改过
     *
     * @param array $retData
     * @return bool
     * @throws \Exception
     */
    protected function verifySign(array $retData){
        $retSign = $retData['sign'];//先不验证加密s
        return true;
        $data = ArrayUtil::removeKeys($retData, ['sign']);

        $values = [
            'return_code'        => $data['code'],
            'return_msg'         => $data['msg'],
            'out_trade_no'       => $data['outTradeNo'],
            'transaction_id'     => $data['transactionId'],
            'pay_type'           => $data['payType'],
            'total_fee'          => $data['totalAmount'],
            'user_id'            => $data['buyerId'],
            'out_transaction_id' => $data['outTransactionId'],
        ];

        $values = ArrayUtil::paraFilter($values);
        //        $values = ArrayUtil::arraySort($values);
        $signStr = ArrayUtil::createLinkstring($values);

        switch($this->config->signType){
            case 'MD5':
                $sign = md5($signStr);
                break;
            default:
                $sign = '';
        }

        return strtoupper($sign) === strtoupper($retSign);
    }

    /**
     * 向客户端返回必要的数据
     *
     * @param array $data
     * @return void
     */
    protected function getRetData(array $data){
        // TODO: Implement getRetData() method.
        $retData = [
            'sign'       => $data['sign'],
            'notify_type'     => $data['notify_type'],
            'notify_time'           => $data['notify_time'],
            'out_trade_no'            => $data['out_trade_no'],
            'total_amount'            => $data['total_amount'] ?? 0,
            'trade_no'            => $data['trade_no'] ?? '',
            'trade_status'            => $data['trade_status'],
        ];
        return $retData;
    }

    /**
     * 根据返回结果，回答支付机构。是否回调通知成功
     *
     * @param boolean $flag 每次返回的bool值
     * @param string  $msg 通知信息，错误原因
     * @return mixed
     */
    protected function replyNotify($flag, $msg = 'OK'){
        if (! $flag) {
            return 'FAIL';
        }
        return 'SUCCESS';
    }
}
